﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.CheckManagement

{
    public partial class SupperForm : DevExpress.XtraEditors.XtraForm
    {
        #region 私有字段
        private readonly int _pageSize = 10;
        private int _pageIndex = 1;
        private int _total = 0;
        private readonly string _baseUrl = "http://localhost:5078/api/Supper/";
        private readonly HttpClient _httpClient;
        #endregion

        #region 构造函数
        public SupperForm()
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
            InitializeComponent();
            InitializeControls();
            BindEvents();
            LoadInitialData();
        }
        #endregion

        #region 初始化和事件绑定
        private void InitializeControls()
        {
            Text = "供应商管理";
            SetupGridColumns();
            SetupRatingColumn();
            SetupGridViewOptions();
        }

        private void SetupGridViewOptions()
        {
            // 设置网格视图的显示选项
            gridView1.OptionsView.ShowAutoFilterRow = false; // 不显示过滤行
            gridView1.OptionsView.ColumnAutoWidth = false; // 禁用自动列宽
            gridView1.OptionsView.ShowGroupPanel = false; // 隐藏分组面板
            gridView1.OptionsCustomization.AllowColumnMoving = true; // 允许列移动
            gridView1.OptionsCustomization.AllowColumnResizing = true; // 允许列宽调整
            gridView1.OptionsView.RowAutoHeight = true; // 自动行高
            gridView1.OptionsView.ShowIndicator = true; // 显示行号
        }

        private void BindEvents()
        {
            this.gridControl1.Load += GridControl1_Load;
            this.btnSearch.Click += async (s, e) => await RefreshData();
            this.btnAdd.Click += AddSupplier;
            this.btnDelete.Click += DeleteSupplier;
            this.btnExport.Click += ExportData;
            this.gridView1.DoubleClick += GridView1_DoubleClick;
        }

        private void LoadInitialData()
        {
            _ = LoadGridDataAsync();
        }
        #endregion

        #region Grid设置
        private void SetupGridColumns()
        {
            // 设置所有列为只读
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in this.gridView1.Columns)
            {
                col.OptionsColumn.AllowEdit = false;
                col.OptionsColumn.ReadOnly = true;
                col.MinWidth = 100; // 设置最小列宽
            }

            // 设置字段名
            supplierCode.FieldName = "SupplierCode";
            supplierName.FieldName = "SupplierName";
            supperAdders.FieldName = "SupplierAddress";
            supperLevel.FieldName = "SupplierLevel";
            supperPhoneOne.FieldName = "SupplierPhoneOne";
            supperPhoneTwo.FieldName = "SupplierPhoneTwo";
            supperDesc.FieldName = "SupplierDesc";
            supperBrief.FieldName = "SupplierBrief";
            supplierRating.FieldName = "SupplierRating";
            isEnabled.FieldName = "IsEnabled";

            // 设置布尔列显示为复选框
            var checkEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
            gridControl1.RepositoryItems.Add(checkEdit);
            isEnabled.ColumnEdit = checkEdit;

            // 设置列宽
            supplierCode.Width = 120;
            supplierName.Width = 200;
            supperAdders.Width = 250;
            supperPhoneOne.Width = 120;
            supperPhoneTwo.Width = 120;
            supperDesc.Width = 250;
            supperBrief.Width = 200;
            supplierRating.Width = 150;
            isEnabled.Width = 80;
        }

        private void SetupRatingColumn()
        {
            var ratingEdit = new DevExpress.XtraEditors.Repository.RepositoryItemRatingControl
            {
                ItemCount = 5,
                ReadOnly = true,
                Appearance = { 
                    ForeColor = Color.Gold
                }
            };
            
            gridControl1.RepositoryItems.Add(ratingEdit);
            supplierRating.ColumnEdit = ratingEdit;
            supplierRating.Width = 150;
        }
        #endregion

        #region 事件处理
        private void GridControl1_Load(object sender, EventArgs e)
        {
            _ = LoadGridDataAsync();
        }

        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            var focusedRow = gridView1.GetFocusedRow() as SupplierDto;
            if (focusedRow != null)
            {
                // TODO: 打开编辑窗口
                MessageBox.Show($"编辑供应商: {focusedRow.SupplierName}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void AddSupplier(object sender, EventArgs e)
        {
            try
            {
                // TODO: 打开添加供应商窗口
                MessageBox.Show("添加供应商功能待实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加供应商时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void DeleteSupplier(object sender, EventArgs e)
        {
            try
            {
                var focusedRow = gridView1.GetFocusedRow() as SupplierDto;
                if (focusedRow == null)
                {
                    MessageBox.Show("请选择要删除的供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (MessageBox.Show($"确定要删除供应商 {focusedRow.SupplierName} 吗？", "确认", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }

                var url = $"{_baseUrl}DeleteSupper?supperCode={focusedRow.SupplierCode}";
                var response = await _httpClient.DeleteAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await RefreshData();
                }
                else
                {
                    MessageBox.Show("删除失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除供应商时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ExportData(object sender, EventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "Excel文件|*.xlsx",
                    Title = "导出Excel",
                    FileName = $"供应商列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                };

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    gridControl1.ExportToXlsx(saveFileDialog.FileName);
                    MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 数据加载
        private async Task RefreshData()
        {
            _pageIndex = 1;
            await LoadGridDataAsync();
        }

        private async Task LoadGridDataAsync()
        {
            try 
            {
                gridControl1.UseWaitCursor = true;
                
                var supplierCode = txtSupplierCode.Text.Trim();
                var supplierName = txtSupplierName.Text.Trim();

                var url = $"{_baseUrl}GetSupperList?pageIndex={_pageIndex}&pageSize={_pageSize}";
                if (!string.IsNullOrEmpty(supplierCode))
                {
                    url += $"&supplierCode={supplierCode}";
                }
                if (!string.IsNullOrEmpty(supplierName))
                {
                    url += $"&supplierName={supplierName}";
                }

                var response = await _httpClient.GetFromJsonAsync<PageResult<SupplierDto>>(url);
                    
                if (response?.Items != null)
                    {
                    UpdateGridData(response);
                    }
                    else
                    {
                        MessageBox.Show("未获取到数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                gridControl1.UseWaitCursor = false;
            }
        }

        private void UpdateGridData(PageResult<SupplierDto> response)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateGridDataInternal(response)));
            }
            else
            {
                UpdateGridDataInternal(response);
            }
        }

        private void UpdateGridDataInternal(PageResult<SupplierDto> response)
        {
            gridControl1.DataSource = null;
            gridControl1.DataSource = response.Items;
            
            // 调整列宽和显示
            gridView1.BestFitColumns();
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView1.Columns)
            {
                if (col.Width < col.MinWidth)
                {
                    col.Width = col.MinWidth;
        }
            }
            
            _total = response.Total;
        }
        #endregion

        #region 数据模型
        public class PageResult<T>
        {
            public int Total { get; set; }
            public int PageIndex { get; set; }
            public int PageSize { get; set; }
            public List<T> Items { get; set; }
            public int Code { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }

        public class SupplierDto
        {
            public string SupplierCode { get; set; } = string.Empty;
            public string SupplierName { get; set; } = string.Empty;
            public string SupplierLevel { get; set; } = string.Empty;
            public string SupplierAddress { get; set; } = string.Empty;
            public string SupplierPhoneOne { get; set; } = string.Empty;
            public string SupplierPhoneTwo { get; set; } = string.Empty;
            public string SupplierDesc { get; set; } = string.Empty;
            public string SupplierBrief { get; set; } = string.Empty;
            public int SupplierRating { get; set; }
            public bool IsEnabled { get; set; }
        }
        #endregion

        private void SupperForm_Load(object sender, EventArgs e)
        {

        }
    }
}